<template>
	<uv-popup ref="loginPopup" mode="center" :customStyle="{ 'border-radius': '20rpx' }" :safeAreaInsetBottom="false"
		:closeable="true" @change="handleChangePopup">
		<view class="logon-box">
			<view class="title-box">
				<image class="img" :src="shopConfigStore?.config?.shopLogo"></image>
				<text class="name">{{ shopConfigStore?.config?.shopName || '登录授权' }} 申请</text>
			</view>
			<view class="desc-box">获取以下权限为您提供服务</view>
			<view class="content-box">
				<view class="tit m-b-20">
					1、获取你的手机号提供更好的账户安全，物流，订单状态提醒等服务（在接下来微信授权手机号的弹窗中选择“允许”）
				</view>
				<view class="tit">
					2、使用我们的相关服务，需要将您的手机号授权给我们。
				</view>
			</view>
			<view class="agreement-box">
				<uv-checkbox-group :customStyle="{ 'flex': 'none' }">
					<uv-checkbox :checked="state.agreement" @change="handleCheckboxChange"></uv-checkbox>
				</uv-checkbox-group>
				<view class="agreement-tit">
					同意 <text class="tit"
						@click="handleRouteNavigateTo(`/pages/subpackage/article/detail/detail?idType=1&id=${shopConfigStore.config?.userAgreementId}`)">《服务协议》</text>
					与 <text class="tit"
						@click="handleRouteNavigateTo(`/pages/subpackage/article/detail/detail?idType=1&id=${shopConfigStore.config?.privacyPolicyId}`)">《隐私协议》</text>
				</view>
			</view>
			<view class="btn-box">
				<view class="btn">
					<uv-button @click="handleCloseAuth" :customStyle="{ 'width': '100%' }" size="normal" :plain="true"
						text="暂不授权"></uv-button>
				</view>
				<view class="btn">
					<!-- #ifdef MP-WEIXIN -->
					<uv-button v-if="state.agreement" :customStyle="{ 'width': '100%' }" openType="getPhoneNumber"
						@getphonenumber="getPhoneNumber" type="success" size="normal" text="确定授权"></uv-button>
					<uv-button v-else @click="handleClickOk" :customStyle="{ 'width': '100%' }" type="success"
						size="normal" text="确定授权"></uv-button>
					<!-- #endif  -->
					<!-- #ifdef MP-ALIPAY  -->
					<uv-button v-if="state.agreement" :customStyle="{ 'width': '100%' ,'position':'relative'}"
						type="success" size="normal">
						<button class="alipay-btn" type="success" size="mini" open-type="getAuthorize"
							scope="phoneNumber" @getAuthorize="getAliPhoneNumber" v-if="state.agreement">
							<view class="btn-tit">确定授权</view>
						</button>
					</uv-button>
					<uv-button v-else @click="handleClickOk" :customStyle="{ 'width': '100%' }" type="success"
						size="normal" text="确定授权"></uv-button>
					<!-- #endif  -->
				</view>
			</view>
		</view>
	</uv-popup>
</template>
<script setup lang="ts">
	import { watch, ref, reactive, onMounted } from 'vue';
	import { useShopConfigStore, useUserInfoStore } from '@/core/store';
	import type { Response } from '@/core/models';
	import { Invitecode, UserToken } from '@/core/consts';
	import { queryLoginPhoneNumber, queryLogin, queryAliPayAppAuthTokenBYCode, queryDecryptPhoneNumberByAli } from '@/core/api';
	import { loginGetCode, handleShowToast, handleRouteNavigateTo } from '@/core/utils';

	/** 获取项目配置 */
	const shopConfigStore = useShopConfigStore();

	/** 获取用户数据 */
	const userInfoStore = useUserInfoStore();

	const props = withDefaults(defineProps<{
		show : boolean,
		goodsDetailData : any,
	}>(), {
		show: false,
		goodsDetailData: {},
	});

	const loginPopup = ref();

	const state = reactive<{
		agreement : boolean;
		sessionAuthIdTool : string;
	}>({
		agreement: false,
		sessionAuthIdTool: "",
	})

	watch(() => props.show, (newVal : boolean) => {
		if (newVal) {
			// #ifdef MP-ALIPAY || MP-WEIXIN
			loginPopup.value.open();
			// #endif

			// #ifndef MP-WEIXIN || MP-ALIPAY 
			handleRouteNavigateTo(`/pages/login/login`)
			// #endif
		} else {
			loginPopup.value.close();
		}
	});

	const emits = defineEmits(['handleChangePopup', 'getUserInfo']);

	onMounted(() => {
		if (Object.keys(userInfoStore.userInfo).length == 0 || !uni.getStorageSync(UserToken)) {
			handleLoginGainToken();
		}
	});

	/** 微信/支付宝 登录 */
	const handleLoginGainToken = () => {
		loginGetCode(async (code : string) => {
			// #ifdef MP-WEIXIN
			const login : Response<any> = await queryLogin({ code, });
			// #endif

			// #ifdef MP-ALIPAY
			const login : Response<any> = await queryAliPayAppAuthTokenBYCode({ id: code });
			// #endif 

			if (login.status) {
				if (login.data.auth) {
					uni.setStorageSync(UserToken, login.data.auth.token);
				}
				if (login.data.user) {
					userInfoStore.setUserInfo(login.data.user);
				}
				state.sessionAuthIdTool = login?.otherData;
			} else {
				state.sessionAuthIdTool = login?.otherData;
				handleShowToast(login.msg);
			}
		})
	}

	/** sku弹框显示或者隐藏 */
	const handleChangePopup = (e : any) => {
		emits('handleChangePopup', e.show)
	}

	/** 勾选版权协议 */
	const handleCheckboxChange = (e : boolean) => {
		state.agreement = e;
	}

	/** 点击确定提醒勾选 */
	const handleClickOk = () => {
		handleShowToast('请先勾选版权协议');
	}

	/** 取消授权 */
	const handleCloseAuth = () => {
		emits('handleChangePopup', false);
		handleShowToast('您已取消授权');
		state.agreement = false;
	}

	/** 微信获取授权手机号 */
	const getPhoneNumber = (e : any) => {
		emits('handleChangePopup', false);
		if (e.errMsg.includes('ok')) {
			let data = {
				sessionAuthId: state.sessionAuthIdTool,
				iv: e.iv,
				encryptedData: e.encryptedData,
			}
			/** 有推荐码的话，带上 */
			if (uni.getStorageSync(Invitecode)) {
				data['invitecode'] = uni.getStorageSync(Invitecode);
			}
			handleLogin(data);
		} else {
			handleShowToast('您已经取消了授权，将无法进行关键业务功能。');
		}
	}

	/** 支付宝获取授权手机号 */
	const getAliPhoneNumber = () => {
		emits('handleChangePopup', false);
		my.getPhoneNumber({
			success: (res : any) => {
				let encryptedData = JSON.parse(res.response);
				let data = {
					sessionAuthId: state.sessionAuthIdTool,
					sign: encryptedData.sign,
					encryptedData: encryptedData.response,
				}
				/** 有推荐码的话，带上 */
				if (uni.getStorageSync(Invitecode)) {
					data['invitecode'] = uni.getStorageSync(Invitecode);
				}
				handleLogin(data);
			}
		})
	}

	/** 去登录获取数据 */
	const handleLogin = async (data : any) => {

		// #ifdef MP-WEIXIN 
		const phoneNumber : Response<any> = await queryLoginPhoneNumber(data);
		// #endif

		// #ifdef MP-ALIPAY 
		const phoneNumber : Response<any> = await queryDecryptPhoneNumberByAli(data);
		// #endif

		if (phoneNumber.status && phoneNumber.data.token) {
			uni.setStorageSync(UserToken, phoneNumber.data.token);
			if (phoneNumber.otherData) {
				userInfoStore.setUserInfo(phoneNumber.otherData);
				uni.removeStorageSync(Invitecode);
				handleShowToast('登录成功', 'success');
				emits('getUserInfo')
			}
		} else {
			handleShowToast('登录失败，请重试');
		}
	}
</script>

<style lang="scss" scoped>
	@import "./coreshop-login-modal.scss";
</style>